import SwiftUI

struct ContentView: View {
    @State private var selectedPID: String?
    @State private var processList: [ProcessInfoItem] = []
    @State private var lastUpdated = Date()

    var body: some View {
        VStack(alignment: .leading) {
            Text("🖤 XUANJI 控制中心").font(.headline)
            Divider()

            HStack {
                Text("总内存:")
                Spacer()
                Text("🧠 \(SystemInfo.getTotalMemoryInGB()) GB")
            }

            HStack {
                Text("可用磁盘:")
                Spacer()
                Text("💾 \(SystemInfo.getAvailableDiskSpace())")
            }

            Divider()

            Text("运行进程").bold()

            List(processList, id: \.pid, selection: $selectedPID) { item in
                HStack {
                    Text("\(item.command)")
                    Spacer()
                    Text("PID: \(item.pid)")
                        .font(.caption)
                        .foregroundColor(.gray)
                }
                .tag(item.pid)
            }
            .frame(height: 200)
            .onAppear {
                // Only load processes if enough time has passed since the last update
                if Date().timeIntervalSince(lastUpdated) > 1 {
                    loadProcesses()
                    lastUpdated = Date()
                }
            }

            HStack {
                Button("Kill -9") {
                    if let pid = selectedPID {
                        killProcess(pid: pid)
                    }
                }
            }

            Spacer()
        }
        .padding()
        .frame(width: 420, height: 500)
    }

    func loadProcesses() {
        let task = Process()
        task.launchPath = "ps"
        task.arguments = ["-ax", "-o", "pid=,comm="]

        let pipe = Pipe()
        task.standardOutput = pipe

        task.launch()
        task.waitUntilExit()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        guard let output = String(data: data, encoding: .utf8) else { return }

        let lines = output.split(separator: "\n")
        processList = lines.compactMap { line in
            let parts = line.trimmingCharacters(in: .whitespaces).split(separator: " ", maxSplits: 1)
            if parts.count == 2 {
                return ProcessInfoItem(pid: String(parts[0]), command: String(parts[1]))
            }
            return nil
        }
    }

    func killProcess(pid: String) {
        let task = Process()
        task.launchPath = "/bin/kill"
        task.arguments = ["-9", pid]
        task.launch()
    }

    func purgeMemory() {
        let task = Process()
        task.launchPath = "/usr/bin/sudo"
        task.arguments = ["/usr/bin/purge"]
        task.launch()
    }
}
